<template>
  <view class="body">
    <view class="headWrapper">
      <view class="personInfo">
        <view class="personInfo-left" v-if="!mobile">
          <button
            class="personTelBtn"
            open-type="getPhoneNumber"
            @getphonenumber="onGetphonenumber"
          >
            <image
              :src="
                imgUrl
                  ? imgUrl
                  : '/static/images/profile.jpg'
              "
              class="profileImg"
            />
          </button>
        </view>
        <view class="personInfo-left" v-else @click="onAvatarChange">
          <button class="personTelBtn" open-type="chooseAvatar" @chooseavatar="onChooseavatar">
            <image
              :src="
                imgUrl
                  ? imgUrl
                  : '/static/images/profile.jpg'
              "
              class="profileImg"
            />
          </button>
        </view>
        <view class="personInfo-right">
          <text class="personName-text">
            {{ nickName ? '微信用户' : '未登录' }}
          </text>
          <text class="personTel" v-if="mobile">{{ mobile }}</text>
          <button
            class="personTelBtn"
            open-type="getPhoneNumber"
            @getphonenumber="onGetphonenumber"
            v-else
          >
            点击登录
          </button>
        </view>
      </view>

      <view class="centerWrapper">
        <view class="advertise">
          <!-- <view
            class="advertiseItem"
            v-for="(item, index) in advertise"
            :key="index"
            @click="navigateTo(item.link)"
          >
            <image :src="item.image" class="advertiseImg" />
            <view class="advertiseText"> {{ item.text }} </view>
          </view> -->
          <view class="advertiseItem" v-if="!isAccessTokenSet">
            <button
              open-type="getPhoneNumber"
              @getphonenumber="onGetCollect"
              style="background-color: #ffff"
            >
              <image
                src="http://xcxtp.njmswl.com/images/profile/starHouse.png"
                role="img"
                class="advertiseImg"
              ></image>
              <view class="advertiseText" style="width: 88px; height: 15px; line-height: 15px"
                >我收藏的房源</view
              >
            </button>
          </view>
          <view class="advertiseItem" v-else @click="navigateTo(1)">
            <image
              src="http://xcxtp.njmswl.com/images/profile/starHouse.png"
              role="img"
              class="advertiseImg"
            ></image>
            <view class="advertiseText">我收藏的房源</view>
          </view>
          <view class="advertiseItem" @click="navigateTo(2)">
            <image
              src="http://xcxtp.njmswl.com/images/profile/openMini.png"
              role="img"
              class="advertiseImg"
            ></image>
            <view class="advertiseText">我也要开通小程序</view>
          </view>
          <view class="advertiseItem" @click="showAddGuide">
            <image
              src="http://xcxtp.njmswl.com/images/profile/addMini.png"
              role="img"
              class="advertiseImg"
            ></image>
            <view class="advertiseText">添加到我的小程序</view>
          </view>
        </view>
        <view class="moreFunctionWrapper">
          <view class="moreText">更多功能</view>
          <view class="moreFunction">
            <view
              class="advertiseItem"
              v-for="(item, index) in moreFunction"
              :key="index"
              @click="moreFunctionClick(item.link)"
            >
              <image :src="item.image" class="advertiseImg" />
              <view class="advertiseText"> {{ item.text }} </view>
            </view>
          </view>
        </view>
        <open-program></open-program>
      </view>
    </view>
  </view>
</template>
<script setup>
import { ref, reactive, nextTick } from 'vue'
import openProgram from '../components/openProgram.vue'
import { getLoginAPI, getSocialLoginAPI } from '@/services/login'
import { onLoad, onTabItemTap } from '@dcloudio/uni-app'
import { getUserInformationAPI } from '@/services/profile'

// 登录成功后更新头像、电话
// 登录获取手机号方法 参数：1.code 2.encryptedData 3.iv
const time = ref()
const scene = ref()
const onGetphonenumber = async (ev) => {
  const encryptedData = ev.detail.encryptedData
    scene.value = uni.getStorageSync('scene')
  const iv = ev.detail.iv
  const res = await getSocialLoginAPI({
    code: ev.detail.code,
    encryptedData: encryptedData,    
    iv: iv,
    sourceUserId:scene.value
  })
  console.log(res)
  const bearer = 'Bearer '
  uni.setStorageSync('appIdKey', res.data.userId)
  uni.setStorageSync('expiresTime', res.data.expiresTime)
  uni.setStorageSync('accessToken', bearer + res.data.accessToken)
    isAccessTokenSet.value = !!uni.getStorageSync('accessToken')
  getUserInformation()
}
//-------------------token过期---------------------------------------------------------------------------------
function myFunction() {
    time.value = uni.getStorageSync('expiresTime')
  // 获取当前系统时间的时间戳
  const currentTimeTimestamp = Date.now()
  // 检查Token是否过期
  if (currentTimeTimestamp >= time.value) {
    uni.removeStorageSync('accessToken')
    uni.removeStorageSync('appIdKey')
    uni.removeStorageSync('expiresTime')
  } else {
  }
}

// 使用 setInterval 每隔一秒钟调用 myFunction
const intervalId = setInterval(myFunction, 1000)

//点击我的收藏--------- 需要登陆 ------- 后才跳转到收藏页面---------------------------------------------
const isAccessTokenSet = ref(!!uni.getStorageSync('accessToken'))
const onGetCollect = async (ev) => {
  console.log('函数走这里')
  const encryptedData = ev.detail.encryptedData
  const iv = ev.detail.iv
  const res = await getSocialLoginAPI({
    code: ev.detail.code,
    encryptedData: encryptedData,
    iv: iv,
  })
  console.log(res)
  const bearer = 'Bearer '
  uni.setStorageSync('appIdKey', res.data.userId)
  uni.setStorageSync('expiresTime', res.data.expiresTime)
  uni.setStorageSync('accessToken', bearer + res.data.accessToken)
  isAccessTokenSet.value = !!uni.getStorageSync('accessToken')
  getUserInformation()
  uni.navigateTo({
    url: `/pages/simplePage/myCollectHouse`,
  })
}

const showAddGuide = () => {
  uni.showModal({
    title: '添加指南',
    content:
      '请按照以下步骤将小程序添加到“我的小程序”中：\n\n1. 点击页面右上角的“...”按钮。\n2. 在弹出的菜单中选择“添加到我的小程序”。',
    showCancel: false,
    confirmText: '我知道了',
    success: () => {
      // 弹窗关闭后的操作，如果有的话
    },
  })
}
// 更多功能列表
const moreFunction = ref()
moreFunction.value = [
  {
    image: 'http://xcxtp.njmswl.com/images/profile/sellHouse.png',
    text: '我要卖房',
    link: '/pages/sellHouse/sellHouse',
  },
  {
    image: 'http://xcxtp.njmswl.com/images/profile/buyHouse.png',
    text: '我要买房',
    link: '/pages/buyHouse/buyHouse',
  },
  {
    image: 'http://xcxtp.njmswl.com/images/profile/introduce.png',
    text: '公司介绍',
    link: '/pages/simplePage/company',
  },
  {
    image: 'http://xcxtp.njmswl.com/images/profile/statement.png',
    text: '隐私协议声明',
    link: '/pages/simplePage/privacy',
  },
]

const navigateTo = (url) => {
  if (url == 1) {
    uni.navigateTo({
      url: '/pages/simplePage/myCollectHouse',
    })
  }
  if (url == 2) {
    uni.navigateTo({
      url: '/pages/simplePage/openMiniProgram',
    })
  }
  if (url == 3) {
    uni.navigateTo({
      url: '/pages/simplePage/rentHouse',
    })
  }
}
onTabItemTap(() => {
  getUserInformation()
})
const imgUrl = ref('')
const mobile = ref('')
const nickName = ref('')
const getUserInformation = async () => {
  const userid = uni.getStorageSync('appIdKey')
  console.log('获取个人信息这个函数执行了嘛')
  const res = await getUserInformationAPI({
    // id:userid
  })
  console.log('看这里》》打印个人信息', res)
  imgUrl.value = res.data?.avatar
  mobile.value = res.data?.mobile
  nickName.value = res.data?.nickname
  console.log('dsadsdsad', imgUrl.value)
}

const onChooseavatar = (e) => {
  uni.uploadFile({
    url: '/admin-api/system/user/profile/update-avatar',
    filePath: e.detail.avatarUrl,
    name: 'avatarFile',
    success: async (res) => {
      const obj = JSON.parse(res.data)
      imgUrl.value = obj.data
      await nextTick()
    },
    fail: (fail) => {
      console.log('上传失败', fail)
    },
  })
}
// 更多功能点击跳转
const moreFunctionClick = (url) => {
  uni.reLaunch({
    url: url, // 假设detail页面需要id参数
  })
}
</script>
<style lang="scss">
page {
  background-color: #f4f5fd;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.body {
  position: relative;
  width: 750rpx;
  height: 1250rpx;
  background-color: #f4f5fd;
  overflow: hidden;
}
.personTelBtn {
  // border: none;
  background-color: transparent;
  width: 100%;
  // width: 100rpx;
  // height: 23rpx;
  // margin-top: 20rpx;
  padding: 0rpx;
  margin: 0rpx;
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 24rpx;
  text-align: left;
  color: #ffffff;
}
.headWrapper {
  width: 100%;
  height: 511rpx;
  padding-top: 164rpx;
  background-image: url(http://xcxtp.njmswl.com/images/profile/bgc.png);
  background-size: 100% 100%;
  background-repeat: no-repeat;
  .personInfo {
    display: flex;
    align-items: center;
    width: 100%;
    height: 120rpx;
    .profileImg {
      border-radius: 50%;
      width: 120rpx;
      height: 120rpx;
      margin-left: 23rpx;
      margin-right: 24rpx;
    }
    .personInfo-right {
      display: flex;
      flex-wrap: wrap;
      .personName-text {
        height: 33rpx;
        font-family: PingFang SC;
        font-weight: 600;
        font-size: 34rpx;
        color: #ffffff;
        line-height: 36rpx;
      }

      .personTel {
        width: 100%;
        height: 23rpx;
        margin-top: 20rpx;
        font-family: PingFang SC;
        font-weight: 400;
        font-size: 24rpx;
        color: #ffffff;
      }
    }
  }
}
.centerWrapper {
  width: 694rpx;
  height: auto;
  margin-top: 40rpx;
  margin-left: 27rpx;
  .advertise {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 695rpx;
    height: 245rpx;
    background: #ffffff;
    border-radius: 15rpx;
    .advertiseItem {
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      align-items: center;
      width: 33%;
      .advertiseImg {
        width: 115rpx;
        height: 115rpx;
      }
      .advertiseText {
        font-family: PingFang SC;
        font-weight: 500;
        font-size: 22rpx;
        color: #000000;
      }
    }
  }
  .moreFunctionWrapper {
    margin-top: 53rpx;
    margin-bottom: 30rpx;
    .moreText {
      width: 100%;
      font-family: PingFang SC;
      font-weight: 600;
      font-size: 34rpx;
      color: #000000;
    }
    .moreFunction {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      align-items: center;
      width: 695rpx;
      height: 350rpx;
      // background: #ffffff;
      border-radius: 15rpx;

      .advertiseItem {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        align-items: center;
        width: 33%;
        .advertiseImg {
          width: 75rpx;
          height: 75rpx;
        }
        .advertiseText {
          width: 100%;
          text-align: center;
          font-family: PingFang SC;
          font-weight: 400;
          font-size: 24rpx;
          color: #000000;
        }
      }
    }
  }
}
</style>
